<template>
  <el-dialog v-model="visible" :title="title" width="600px" @close="handleClose">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="主机名称" prop="hostname">
        <el-input v-model="form.hostname" placeholder="请输入主机名称" />
      </el-form-item>
      <el-form-item label="外网IP" prop="publicIp">
        <el-input v-model="form.publicIp" placeholder="请输入外网IP" />
      </el-form-item>
      <el-form-item label="内网IP" prop="localIp">
        <el-input v-model="form.localIp" placeholder="请输入内网IP" />
      </el-form-item>
      <el-form-item label="SSH端口" prop="port">
        <el-input-number v-model="form.port" :min="1" :max="65535" />
      </el-form-item>
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" type="password" placeholder="请输入密码" show-password />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { computed, reactive, ref, watch } from "vue";
import { createHost, updateHost } from "@/api/res/host-api";

const props = defineProps({
  modelValue: Boolean,
  host: Object,
});

const emit = defineEmits(["update:modelValue", "success"]);

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit("update:modelValue", value),
});

const title = computed(() => (props.host?.id ? "编辑主机" : "新增主机"));

const formRef = ref();
const form = reactive({
  id: undefined,
  hostname: "",
  publicIp: "",
  localIp: "",
  port: 22,
  username: "",
  password: "",
});

const rules = reactive({
  hostname: [{ required: true, message: "请输入主机名称", trigger: "blur" }],
  publicIp: [{ required: true, message: "请输入外网IP", trigger: "blur" }],
  localIp: [{ required: true, message: "请输入内网IP", trigger: "blur" }],
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
});

watch(
  () => props.host,
  (newVal) => {
    if (newVal) {
      Object.assign(form, newVal);
    }
  },
  { immediate: true }
);

const handleClose = () => {
  visible.value = false;
};

const handleSubmit = async () => {
  try {
    await formRef.value.validate();
    if (form.id) {
      await updateHost(form.id, form);
    } else {
      await createHost(form);
    }
    emit("success");
  } catch (error) {
    console.error("提交失败:", error);
  }
};
</script>
